package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class ParameterServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("----------------doGet(未考虑乱码)----------------");
        String usernameL = request.getParameter("username");
        System.out.println("用户名: " + usernameL);

        System.out.println("----------------doGet(解决乱码)----------------");
        //getParameter( ) 获取请求的参数
        String username = request.getParameter("username");
        /*解决GET获取请求中文乱码问题*/
        //1.先以iOS8859-1进行编码
        //2.再以utf-8进行解码
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        String password = request.getParameter("password");
        //getParameterValues() 获取请求的参数(多个值的时候使用)
        String[] hobbies = request.getParameterValues("hobby");

        System.out.println("用户名: " + username);
        System.out.println("密码: " + password);
        System.out.println("兴趣爱好: " + Arrays.toString(hobbies));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("----------------doPost(解决乱码)----------------");
        //设置请求体的字符集为UTF-8，从而解决post请求的中文乱码问题
        //要在获取请求参数之前使用才有效
        req.setCharacterEncoding("UTF-8");
        //getParameter( ) 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //getParameterValues() 获取请求的参数(多个值的时候使用)
        String[] hobbies = req.getParameterValues("hobby");

        System.out.println("用户名: " + username);
        System.out.println("密码: " + password);
        System.out.println("兴趣爱好: " + Arrays.toString(hobbies));
    }
}
